#!/usr/bin/python

from dates import DateUtils
import datetime, re, os, sys
from platform import system
 
class FileFilter(object):
    #some comment
    def __init__(self):
        self.du = DateUtils()
        self.minuserchars = 1 #should be plat specific

    def byNameLiteral(self, fullpath, basefilename, exactly=True, prepend=None, append=None): 
        '''
            fullpath == (prepend + basefilename + append) --> True/False
        '''
        if exactly == True:
            #use base only
            return fullpath == basefilename
        #assume here after exactly=False so no need to check
        elif type(prepend) == str and type(append) == str:
            return fullpath == '%s%s%s'%(prepend, basefilename, append)
        elif type(prepend) == str:
            return fullpath == '%s%s'%(prepend, basefilename)
        elif type(append) == str:
            return fullpath == '%s%s'%(basefilename, append)


    def byRegex(self, fullpath, pattern):
        '''
            please enter raw string for pattern
        @param fullpath: regex string pattern or compiled regex
        '''
        if not os.path.exists(fullpath):
            return False
        basepath = os.path.basename(fullpath)
        #better to have pre-compiled?
        #type object needs lazy loading. not create for every iteration
        if isinstance(pattern, type(re.compile(''))):
            return pattern.match(fullpath)
        #potential speed up if remove module lookup
        regex = re.compile(pattern)
        result = regex.match(fullpath)
        return bool(result)

    def byDate(self, fullpath, filterdate, filetime='mtime', datetype='date'):
        '''
            fullpath = desc of it
            filterdate = desc of ... 
            filetime = ....
            datetype = ....
        '''
        if type(filterdate) != datetime.datetime and type(filterdate) != datetime.date:
            raise TypeError('filterdate requires datetime.datetime.{{datetime/date}}')
        if type(filterdate) != getattr(datetime, datetype):
            raise ValueError('filterdate and datetype must be the same')
        if not os.path.exists(fullpath):
            return False
        filedate = self.du.dateFromFile(fullpath, filetime, datetype)
        return filedate == filterdate

    #NOT FINISHED
    def byOwner(self, fullpath, user='', userasid=False, ownershiptype='effective'):
        pass
        raise NotImplementedError('Differ development until lower order functions done and tested.')
        '''
            user='' --> assume effective
            check ownership of file
        '''

        if system() == 'Windows':
            raise NotImplementedError
        real, effective, saved = os.getresuid()
        if not os.path.exists(fullpath):
            pass#return False
        if type(user) != str:
            raise ValueError('user argument must be type str')
        if userasid == True:
            if len(user) < self.minuserchars:
                raise ValueError('must specify user numeric id')
            else:
                numericid = int(user)
        else:
            if user == '':
                numericid = getattr(locals, ownershiptype)
            else:
                pass #convert username to numeric id


    def byGroup(self):
        pass


    def byRole(self):
        pass


    def byUser(self):
        pass


def main_test():
    filenamelist = ('123kdd123', '123kdd', 'kdd123', 'kdd', r'C:\Users\mahdih.ALAHLI\Downloads\unix_projects\abkutils\touched')
    ff = FileFilter()
    resultlist = [f for f in \
            [fe for fe in filenamelist] if ff.byNameLiteral(f, 'kdd', exactly=False, append='123')]
    print(resultlist)

    resultlist2 = [f for f in \
            filenamelist if ff.byDate(f, datetime.date.today(), datetype='date')]
    print(resultlist2)

    resultlist3 = [f for f in \
            filenamelist if ff.byRegex(f, r'\d+[a-z]+\d+')]
    print(resultlist3) 


if __name__ == '__main__':
    main_test()
